package org.gradle.internal.instantiation.generator;

import org.gradle.internal.extensibility.ExtensibleDynamicObject;
import org.gradle.internal.instantiation.InstanceGenerator;
import org.gradle.internal.instantiation.InstantiatorFactory;
import org.gradle.internal.metaobject.AbstractDynamicObject;
import org.gradle.internal.metaobject.BeanDynamicObject;
import org.gradle.internal.metaobject.DynamicObject;
import org.gradle.internal.service.ServiceLookup;

import javax.annotation.Nullable;

/**
 * Used by extensible instances generated by {@link AsmBackedClassGenerator}.
 */
public class MixInExtensibleDynamicObject extends ExtensibleDynamicObject {
    // Used by generated code
    public MixInExtensibleDynamicObject(Object decoratedObject, Class<?> publicType, @Nullable DynamicObject selfProvidedDynamicObject, ServiceLookup services) {
        super(decoratedObject, wrap(decoratedObject, publicType, selfProvidedDynamicObject), instantiator(services));
    }

    private static InstanceGenerator instantiator(ServiceLookup services) {
        InstantiatorFactory instantiatorFactory = (InstantiatorFactory) services.get(InstantiatorFactory.class);
        return instantiatorFactory.decorateLenient(services);
    }

    private static AbstractDynamicObject wrap(Object delegateObject, Class<?> publicType, DynamicObject dynamicObject) {
        if (dynamicObject != null) {
            return (AbstractDynamicObject) dynamicObject;
        }
        return new BeanDynamicObject(delegateObject, publicType);
    }
}
